<template>
  <div class="edit-page-wrap">
    <Head title="广告信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="广告名称" prop="advName">
            <el-input
              v-model.trim="ruleForm.advName"
              placeholder="请输入广告名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="广告类型" prop="advType">
            <el-radio-group
              v-model="ruleForm.advType"
              v-for="(item, index) in optionsS.advType"
              :key="index"
              @change="handleChangeType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.advType === '0'"
            label="广告图片"
            prop="advPicture"
            required
          >
            <QcUpload
              :valueModel="ruleForm.advPicture"
              :size="1"
              type="img1"
              :tip="getImgTip()"
              @on-success="handleSuccessPic"
              @before-upload="beforeUploadPic"
              @on-error="handleErrorPic"
            ></QcUpload>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.advType === '1'"
            label="广告内容"
            prop="advContent"
          >
            <el-input
              v-model.trim="ruleForm.advContent"
              placeholder="请输入广告内容"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="广告位置" prop="advLocation">
            <qc-select
              :value="ruleForm.advLocation"
              :options="optionsS.advLocation"
              placeholder="请选择广告位置"
              @change="handleAdvLocation"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="投放地域" prop="putArea">
            <QcTree
              :setCheckedKeys="ruleForm.putArea.split(',')"
              :data="optionsS.area"
              :showCheckbox="true"
              @handleCheck="handleCheckArea"
            ></QcTree>
          </el-form-item>
          <el-form-item label="投放目标用户" prop="targetUser" class="has-tips">
            <el-radio-group
              v-model="ruleForm.targetUser"
              v-for="(item, index) in optionsS.targetUser"
              :key="index"
              @change="handleChangeUser"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.targetUser === '1'
                  ? '选定企业后，广告仅对所选企业的用户展示'
                  : ruleForm.targetUser === '0'
                  ? '广告对所有用户展示，含未登录用户'
                  : ''
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.targetUser === '1'"
            label=""
            prop="orgArr"
          >
            <QcTree
              ref="treeOrgRef"
              :setCheckedKeys="ruleForm.orgArr"
              :data="optionsS.org"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckOrg"
            ></QcTree>
          </el-form-item>
          <el-form-item label="广告主" prop="advEr">
            <el-input
              v-model.trim="ruleForm.advEr"
              placeholder="请输入广告主"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="广告跳转" prop="jumpType">
            <el-radio-group
              v-model="ruleForm.jumpType"
              v-for="(item, index) in optionsS.jumpType"
              :key="index"
              @change="handelJumpType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.jumpType === '1'"
            label="活动"
            prop="activityType"
          >
            <qc-select
              :value="ruleForm.activityType"
              :options="optionsS.activityType"
              placeholder="请选择活动"
              @change="handleActivityType"
            >
            </qc-select>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.jumpType === '2'"
            label="链接地址"
            prop="jumpConnection"
          >
            <el-input
              v-model.trim="ruleForm.jumpConnection"
              placeholder="请输入链接地址"
              maxlength="200"
              clearable
            />
          </el-form-item>
          <el-form-item label="投放时间" prop="deliveryTime">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.deliveryTime"
                popper-class="qc-date"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                valueFormat="YYYY-MM-DD HH:mm"
                format="YYYY-MM-DD HH:mm"
                :disabled-date="disabledDate"
                :default-time="[
                  new Date(0, 0, 0, 0, 0, 0),
                  new Date(0, 0, 0, 23, 59, 59),
                ]"
              />
            </div>
          </el-form-item>
          <el-form-item label="展示优先级" prop="showPriority">
            <el-input
              v-model.trim="ruleForm.showPriority"
              placeholder="优先级仅需输入1-99，优先级越小越靠前"
              maxlength="2"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import QcUpload from '@/components/qcUpload/index.vue';
import { FormInstance, FormRules } from 'element-plus';
import {
  saveAdvertisement,
  updateAdvertisement,
  getAdvertisement,
  queryAdUserActivity,
} from '@/service/apis/market';
import { queryDicByParent, queryRegionTwoTree } from '@/service/apis/api';
import { queryVehicle } from '@/service/apis/org';
import { IS_INT } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const treeOrgRef = ref();

const getImgTip = () => {
  const str = '温馨提示：只能上传jpg/jpeg/png文件，且不超过2M';
  if (ruleForm.advLocation === '0') {
    // 弹窗广告
    return `${str}（建议尺寸：342*400）`;
  } else if (ruleForm.advLocation === '1') {
    // 充电界面
    return `${str}（建议尺寸：343*120）`;
  } else if (ruleForm.advLocation === '2') {
    // 客户服务中心
    return `${str}（建议尺寸：375*143）`;
  }
  return str;
};

const optionsS = reactive({
  advType: [] as any,
  advLocations: [] as any, // 字典
  advLocation: [] as any, // 可选下拉
  area: [] as any,
  targetUser: [] as any,
  org: [] as any,
  jumpType: [] as any,
  activityType: [] as any,
});

// 字典
queryDicByParent({
  listDtos: ['advType', 'advLocation', 'targetUser', 'jumpType'],
}).then((res: any) => {
  optionsS.advType = res.advType;
  optionsS.advLocations = res.advLocation;
  optionsS.targetUser = res.targetUser;
  optionsS.jumpType = res.jumpType;
  handleChangeType();
});

// 投放地域树数据
queryRegionTwoTree({}).then((res: any) => {
  optionsS.area = res;
});

// 获取企业树数据   企业-车辆机构
const queryVehicleTree = () => {
  queryVehicle({}).then((res: any) => {
    optionsS.org = res;
  });
};

// 获取用户活动下拉数据
const getUserActivity = () => {
  queryAdUserActivity(ruleForm.activityType).then((res: any) => {
    optionsS.activityType = res;
  });
};

if (id) {
  getAdvertisement(id).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      ruleForm.orgArr = res.orgIds.split(',');
      if (res.jumpType === '1') {
        getUserActivity();
      }
      handleChangeType();
      handleChangeUser();
      ruleForm.deliveryTime = [
        ruleForm.deliveryStart.substring(0, 16),
        ruleForm.deliveryEnd.substring(0, 16),
      ];
    }
  });
}

const ruleForm: any = reactive({
  id: '',
  advName: '', //广告名称
  advType: '0', //广告类型
  advPicture: '', //广告图片
  advContent: '', //广告内容
  advLocation: undefined as any, //广告位置
  putArea: '', // 投放地域
  targetUser: '0', //投放目标用户
  orgIds: '', // 企业ids
  orgArr: [] as any, // 企业树ids
  advEr: '', // 广告主
  jumpType: '0', //广告跳转
  activityType: undefined as any, // 活动
  type: '', // 活动类型
  jumpConnection: '', // 链接地址
  deliveryTime: [] as any, //投放时间-组件
  deliveryStart: '',
  deliveryEnd: '',
  showPriority: '', // 展示优先级
});

const errPic = ref('');
const checkPic = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (errPic.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errPic.value === 'size') {
      callback(new Error('上传的图片大于1M'));
    } else if (errPic.value === 'error') {
      callback(new Error('上传失败'));
    } else {
      callback(new Error('请选择广告图片'));
    }
  }
  callback();
};

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
const checkTime = (rule: any, value: any, callback: any) => {
  if (new Date(value[1]).getTime() < new Date().getTime()) {
    callback(new Error('结束时间不能小于当前时间'));
  }
  callback();
};

const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (ruleForm.targetUser === '1' && arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  advName: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
  advType: [
    { required: true, message: '请选择广告类型', trigger: ['blur', 'change'] },
  ],
  advPicture: [{ validator: checkPic, trigger: 'change' }],
  advContent: [{ required: true, message: '请输入广告内容', trigger: 'blur' }],
  advLocation: [
    { required: true, message: '请选择广告位置', trigger: ['blur', 'change'] },
  ],
  putArea: [
    { required: true, message: '请选择投放地域', trigger: ['blur', 'change'] },
  ],
  targetUser: [
    {
      required: true,
      message: '请选择投放目标用户',
      trigger: ['blur', 'change'],
    },
  ],
  orgArr: [
    { required: true, message: '请选择企业', trigger: ['blur', 'change'] },
    { validator: checkTreeVehicles, trigger: ['blur', 'change'] },
  ],
  advEr: [{ required: true, message: '请输入广告主', trigger: 'blur' }],
  jumpType: [
    { required: true, message: '请选择广告跳转', trigger: ['blur', 'change'] },
  ],
  activityType: [
    { required: true, message: '请选择活动', trigger: ['blur', 'change'] },
  ],
  jumpConnection: [
    { required: true, message: '请输入链接地址', trigger: 'blur' },
  ],
  deliveryTime: [
    { required: true, message: '请选择投放时间', trigger: ['blur', 'change'] },
    { validator: checkTime, trigger: ['blur', 'change'] },
  ],
  showPriority: [
    {
      pattern: IS_INT,
      message: '请输入正确的优先级（1-99）',
      trigger: 'blur',
    },
  ],
});

//广告图片
const handleSuccessPic = (val: any) => {
  ruleForm.advPicture = val;
  ruleFormRef?.value?.validateField('advPicture');
};
const handleErrorPic = () => {
  errPic.value = 'error';
  ruleFormRef?.value?.validateField('advPicture');
};
const beforeUploadPic = (type: string) => {
  errPic.value = type;
  if (type) {
    ruleFormRef?.value?.validateField('advPicture');
  }
};

const handleAdvLocation = (e: any) => {
  ruleForm.advLocation = e;
};

const handleActivityType = (e: any) => {
  ruleForm.activityType = e;
  ruleForm.type = optionsS.activityType.find(
    (item: any) => item.value === e
  ).data;
};

const handleChangeType = (e?: any) => {
  if (e) {
    ruleForm.advLocation = undefined as any;
  }
  const timer = setTimeout(() => {
    ruleFormRef.value?.clearValidate('advLocation');
    clearTimeout(timer);
  });
  optionsS.advLocation = [];
  if (ruleForm.advType === '0') {
    optionsS.advLocation = optionsS.advLocations.filter(
      (item: any) => item.value !== '3'
    );
  } else if (ruleForm.advType === '1') {
    optionsS.advLocation = optionsS.advLocations.filter(
      (item: any) => item.value !== '0' && item.value !== '2'
    );
  }
};

const handleChangeUser = () => {
  if (ruleForm.targetUser === '1' && optionsS.org.length === 0) {
    queryVehicleTree();
  }
};

const handleCheckArea = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.putArea = checkedChildData.toString();
};

const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.orgArr = checkedChildData;
};

const handelJumpType = () => {
  if (ruleForm.jumpType === '1' && optionsS.activityType.length === 0) {
    getUserActivity();
  }
};

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const form = { ...ruleForm };
  form.deliveryStart = `${ruleForm.deliveryTime[0]}:00`;
  form.deliveryEnd = `${ruleForm.deliveryTime[1]}:59`;
  if (!form.showPriority) {
    form.showPriority = '99';
  }

  if (form.jumpType === '0') {
    form.jumpConnection = '';
    form.activityType = '';
    form.type = '';
  } else if (form.jumpType === '1') {
    form.jumpConnection = '';
  } else if (form.jumpType === '2') {
    form.activityType = '';
    form.type = '';
  }
  // 投放用户
  if (form.targetUser === '1') {
    const arr: any = [];
    const treeOrg = treeOrgRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    form.orgIds = arr.toString();
  }
  console.log('ru---', form, ruleForm);
  if (id) {
    updateAdvertisement(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveAdvertisement(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>